#include <iostream>
#include "ex02-library.h"
using namespace std;

// Task 2(a).  Implement this function
unsigned int length(Elem *list) {
    // Write your code here
    if(list->next == nullptr) {
        return list->times;
    }
    else {
        return list->times + length(list->next);
    }
}

// Task 2(b).  Implement this function
Elem* append(Elem *list, int v) {
    // Write your code here
    Elem* head = list;
    while(list->next != nullptr) {
        list = list->next;
    }
    if (v == list->value) {
        list->times += 1;        
    } else {
        Elem* tmp = new Elem{v,1,nullptr}; // 动态内存分配， {}中放初值
        list->next = tmp;
    }
    return head;
}

// Task 2(c).  Implement this function
Elem* buildRLEList(int *data, unsigned int n) {
    // Write your code here
    Elem* list =  new Elem{data[0], 1, nullptr};
    for(unsigned int i=1; i<n; i++) {
        list = append(list,data[i]);
        cout << length(list) << endl;
    }
    return list;
}

// Do not modify
void displayRLEList(Elem *list) {
    if (list == nullptr) {
        return;
    }
    cout << " " << list->value << " (x" << list->times << ")";
    displayRLEList(list->next);
}
